package org.yxing.palpalgps.activity;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.yxing.palpalgps.AbstractActivity;
import org.yxing.palpalgps.ActionBar;
import org.yxing.palpalgps.ActionBar.OnActionBarListener;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.utils.ErrorMessage;
import org.yxing.palpalgps.utils.Helper;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class PhotoViewActivity extends AbstractActivity implements OnClickListener, OnActionBarListener{
    
    private static final String TAG = PhotoViewActivity.class.getSimpleName();
    
    private int id;
    
    private ArrayList<String> data;
    
    private ImageView photoView;
    
    private Display mDisplay;
    
    private TextView currentNum;
    private TextView textViewCount;
    
    /**
     * 返回到照片列表时，是否刷新数据
     */
    private boolean isReloadPhotoList = false;
    
    /**
     * 图像显示的宽
     */
    private float newWidth;
    private Matrix mMatrix;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_view);
        setTitle(getString(R.string.photo_view));
        addActionBarItem(ActionBar.Type.Trashcan);
        getActionBar().setOnActionBarListener(this);
        
        photoView = (ImageView) findViewById(R.id.photoView);
        id = getIntent().getIntExtra("id", 0);
        currentNum = (TextView) findViewById(R.id.currentNum);
        textViewCount = (TextView) findViewById(R.id.count);
        
        //adapter
        data = getIntent().getStringArrayListExtra("data");
        
        //获取屏幕大小
        mDisplay = getWindowManager().getDefaultDisplay();
        
        //照片显示的高和宽
        newWidth = (float) mDisplay.getWidth();
        
        //create matrix
        mMatrix = new Matrix();
        
        ((Button) findViewById(R.id.buttonPrev)).setOnClickListener(this);
        ((Button) findViewById(R.id.buttonNext)).setOnClickListener(this);
        
        init();
    }
    
    private void init() {
        int count = data.size();
        textViewCount.setText(Integer.toString(count));
        if (id >= count)
            id = count - 1;
        showPhoto();
    }
    
    private void showPhoto() {
        pd.show();
        currentNum.setText(Integer.toString((id+1)));
        new Thread(runnable).start();
    }
    
    private String getImageUrl (String pid) {
        return Helper.getPictureUrl(pid);
    }
    
    private String getDeleteUrl() {
        return "photo/delete";
    }
    
    private Runnable runnable = new Runnable(){
        public void run() {
            String pid = data.get(id);
            String src = getImageUrl(pid);
            
            try {
                URL url = new URL(src);
                InputStream is = (InputStream) url.getContent();
                Bitmap bmp = BitmapFactory.decodeStream(is);
                is.close();
                mHandler.sendMessage(mHandler.obtainMessage(0, bmp));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pd.cancel();
            Bitmap bm = (Bitmap) msg.obj;
            int width = bm.getWidth();
            int height = bm.getHeight();
            float newHeight = height * newWidth / width;
            mMatrix.reset();
            mMatrix.postScale(newWidth/width, newHeight/height);
            bm = Bitmap.createBitmap(bm, 0, 0, width, height, mMatrix, true);
            photoView.setImageBitmap(bm);
        }
    };
    
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.buttonPrev:
            if (id > 0) {
                id --;
                showPhoto();
            } 
            break;
        case R.id.buttonNext:
            if (id < data.size() - 1) {
                id ++;
                showPhoto();
            }
            break;
        }
    }
    
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra(PhotoGridActivity.TAG_REFLASH, isReloadPhotoList);
            setResult(RESULT_OK, intent);
        }
        return super.onKeyUp(keyCode, event);
    }
    
    private void delete() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.are_you_sure_delete));
        builder.setPositiveButton(getString(R.string.ok), new Dialog.OnClickListener(){
            public void onClick(DialogInterface dialog, int which) {
                
                String url = getDeleteUrl();
                AsyncRequest resp = new AsyncRequest(PhotoViewActivity.this);
                List<BasicNameValuePair> params = OAuth.createAuthParams();
                params.add(new BasicNameValuePair("pid", data.get(id)));
                //delete from server
                resp.fetch(url, params, new AsyncRequest.FetchListener() {
                    
                    public void onComplete(JSONObject response) {
                        isReloadPhotoList = true;
                        data.remove(id);
                        init();
                        displayToast(getString(R.string.toast_delete_success));
                    }
                    
                    public void onError(int code, String msg) {
                       displayToast(msg);
                    }
                });
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), null);
        builder.show();
    }
    
    public void onActionBarItemClick(int position) {
        switch (position) {
        case 0:
            delete();
            break;
        }
    }
}
